package com.ytc.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ytc.commons.constants.CommonConstants;
import com.ytc.commons.constants.CourseConstants;
import com.ytc.commons.enums.ErrorCode;
import com.ytc.commons.model.dto.CourseAuditDto;
import com.ytc.commons.model.dto.CourseBaseDto;
import com.ytc.commons.model.dto.CourseDto;
import com.ytc.commons.model.dto.PageRequest;
import com.ytc.commons.model.vo.CourseBaseVo;
import com.ytc.commons.model.vo.PageResponseResult;
import com.ytc.commons.model.vo.ResponseResult;
import com.ytc.commons.utils.BeanHelper;
import com.ytc.content.config.MinioProperties;
import com.ytc.content.domain.CourseBase;
import com.ytc.content.domain.Teachplan;
import com.ytc.content.mappers.CourseBaseMapper;
import com.ytc.content.service.CourseBaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ytc.content.service.TeachplanService;
import com.ytc.web.exception.BusinessException;
import com.ytc.web.interceptor.AuthInfoHolder;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 * @since 2023-04-01
 */
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {


    /**
     * 分页查询当前机构的课程列表
     */
    @Override
    public ResponseResult courseList(PageRequest request, CourseDto dto) {
        //创建分页参数
        Page<CourseBase> pageParam = new Page<>(request.getPageNo(),request.getPageSize());

        //创建查询条件
        LambdaQueryWrapper<CourseBase> qw = new LambdaQueryWrapper<>();
        //以下为条件查询的条件  coursename 。状态、类型
        //课程名称
        String courseName = dto.getCourseName();
        if(!StringUtils.isEmpty(courseName)) {
            qw.like(CourseBase::getName,"%"+courseName+"%");
        }

        //课程审核状态
        String auditStatus = dto.getAuditStatus();
        if(!StringUtils.isEmpty(auditStatus)) {
            qw.eq(CourseBase::getAuditStatus,auditStatus);
        }
        //课程类型
        String teachmode = dto.getTeachmode();
        if(!StringUtils.isEmpty(teachmode)) {
            qw.eq(CourseBase::getTeachmode,teachmode);
        }
        qw.eq(CourseBase::getStatus,CommonConstants.USING_FLAG); //查询课程状态为使用中

        if(!StringUtils.isEmpty(dto.getAuditStatus())) {
            qw.eq(CourseBase::getAuditStatus,dto.getAuditStatus());
        }
        /*
        设置机构id
        qw.eq(CourseBase::getCompanyId, AuthInfoHolder.getCompanyId());
        */
        Long companyId = AuthInfoHolder.getCompanyId();

        System.out.println("打印企业id666666666666666666666666666666666666666"+companyId);

        //分页查询
        Page<CourseBase> page =this.page(pageParam, qw);//分页起始条数Page，查询条件QueryWarrper
        //转化PageResponseResult
        return new PageResponseResult(page.getTotal(), page.getRecords());
    }


    //上传课程封面图片（用到了minio）
    @Autowired
    private MinioClient client;
    @Autowired
    private MinioProperties properties;
    @Override
    public ResponseResult<String> upload(MultipartFile uploadFile) throws Exception {
        //文件输入流
        InputStream inputStream = uploadFile.getInputStream();
        //指定文件上传的位置和文件名称   /images/2022/07/17/uuid +filename
        String filepath = "/images/" + new SimpleDateFormat("yyyy/MM/dd/")
                .format(new Date()) +
                UUID.randomUUID().toString() + uploadFile.getOriginalFilename();

        //、构造PutObjectArgs参数，并发送请求
        PutObjectArgs objectArgs = PutObjectArgs.builder()
                .contentType("image/jpg").contentType("image/jpeg") //文件类型
                .stream(inputStream, inputStream.available(), -1) //文件流
                .bucket(properties.getBucket()) //存储空间
                .object(filepath) //文件
                .build();
        client.putObject(objectArgs);
        //5、拼接访问地址
        String urlPath = properties.getDomain()+"/"+properties.getBucket()+ filepath;
        return ResponseResult.okResult(urlPath);
    }

    //保存课程
    @Autowired
    private TeachplanService teachplanService;
    @Override
    public ResponseResult<CourseBaseVo> saveCourseBase(CourseBaseDto dto) {

        //1.构造保存对象
          CourseBase courseBase = BeanHelper.copyProperties(dto,CourseBase.class);

        //2.设置必填项目（企业名称，审核状态，删除状态，时间）
          courseBase.setCompanyName(AuthInfoHolder.getAuthInfo().getCompanyName());
          courseBase.setCompanyId(AuthInfoHolder.getAuthInfo().getCompanyId());
          courseBase.setStatus(CommonConstants.USING_FLAG);
          courseBase.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS); //审核状态
        courseBase.setCreateDate(new Date());
        //3.设置章节数 //新建一般没有章节后期在设置先设置为0
         courseBase.setPlanNum(0);
        //4.保存
        Boolean save = this.save(courseBase);
        if(!save){
            throw new BusinessException(ErrorCode.ADDEERROR);
        }

        //课程保存的同时需要有个一级大纲来装他的章节
        //补充：保存一级课程大纲
        Teachplan t = new Teachplan();
        t.setPname(courseBase.getName());
        t.setParentid(0l); //他的父级目录
        t.setGrade(CourseConstants.FIRST_LEVEL);  //第几级目录
        t.setCourseId(courseBase.getId());
        t.setStatus(CommonConstants.USING_FLAG);
        t.setCreateDate(new Date());
        t.setCompanyId(AuthInfoHolder.getCompanyId());

        teachplanService.save(t);
        //5.返回
        CourseBaseVo vo = new CourseBaseVo();
        vo.setCourseBaseId(courseBase.getId());
        return ResponseResult.okResult(vo);
    }

    //逻辑删除
    @Override
    public void updateStatus(Long courseId) {

        LambdaUpdateWrapper<CourseBase> qww = new LambdaUpdateWrapper<>();
        qww.set(CourseBase::getStatus,CommonConstants.DELETE_FLAG);//修改状态为删除
        qww.eq(CourseBase::getId,courseId);
        this.update(qww);
    }

    //根据id更新课程
    /*
    * */
    @Override
    public ResponseResult<CourseBaseVo> updateCourse(CourseBaseDto dto) {

        CourseBase courseBase = BeanHelper.copyProperties(dto, CourseBase.class);
        this.updateById(courseBase);

        CourseBaseVo vo = new CourseBaseVo();
        vo.setCourseBaseId(dto.getId());

        return ResponseResult.okResult(vo);

    }

    ////机构提交审核(修改状态)
    @Override
    public ResponseResult commit(Long courseBaseId) {
        //1.根据id查询
        CourseBase courseBase = this.getById(courseBaseId);
        //2.判断是否可以提交(如果不是未提交则抛异常)
        if(!courseBase.getAuditStatus().equals(CourseConstants.AUDIT_UNPAST_STATUS)&&
           !courseBase.getAuditStatus().equals(CourseConstants.AUDIT_DISPAST_STATUS)){ //
            throw new BusinessException(ErrorCode.ERROR);
        }
        //3.更新状态
        courseBase.setAuditStatus(CourseConstants.AUDIT_COMMIT_STATUS);
        this.updateById(courseBase);
        return ResponseResult.okResult();
    }


    //管理端平台审核
    @Override
    public ResponseResult approve(CourseAuditDto dto) {
        //1.根据课程ID查到课程
        CourseBase courseBase = this.getById(dto.getCourseBaseId());
        //2.判断课程状态
        if(!courseBase.getAuditStatus().equals(CourseConstants.AUDIT_COMMIT_STATUS)){
            throw new BusinessException(ErrorCode.ERROR);
        }
        //3.更新状态和意见
        courseBase.setAuditStatus(dto.getAuditStatus());
        courseBase.setAuditMind(dto.getAuditMind());
         this.updateById(courseBase);
        return ResponseResult.okResult();
    }
}
